import NativeToast, {Icon, Options, CustomOptions} from '~/specs/NativeToast';
import {Platform} from 'react-native';
import GlyphsMap from '@/assets/fonts/icon-mapping.json';
type ToastType = 'success' | 'warning' | 'error';
type Position = 'TOP' | 'CENTER' | 'BOTTOM';

interface ToastIconConfig {
  name: ToastType;
  color?: string;
  size?: number;
}

interface ToastConfig {
  duration?: number;
  position?: Position;
  message: string;
}

class Toast {
  private static instance: Toast;
  private static readonly DEFAULT_ICON_SIZE = 24;
  private static readonly DEFAULT_ICON_COLOR = '#ffffff';
  private static readonly DEFAULT_DURATION = Platform.OS === 'ios' ? 2 : 2000;
  private static readonly DEFAULT_POSITION: Position = 'CENTER';

  private constructor() {}

  public static getInstance(): Toast {
    if (!Toast.instance) {
      Toast.instance = new Toast();
    }
    return Toast.instance;
  }
  public showToast(options: Options) {
    NativeToast.showToast(options);
  }
  private createToastConfig(options: ToastConfig): Options {
    return {
      duration: options.duration ?? Toast.DEFAULT_DURATION,
      position: options.position ?? Toast.DEFAULT_POSITION,
      message: options.message,
    };
  }

  public success(config: ToastConfig): void {
    this.show({
      ...this.createToastConfig(config),
      icon: this.getIcon({name: 'success'}),
    });
  }

  public warning(config: ToastConfig): void {
    this.show({
      ...this.createToastConfig(config),
      icon: this.getIcon({name: 'warning'}),
    });
  }

  public error(config: ToastConfig): void {
    this.show({
      ...this.createToastConfig(config),
      icon: this.getIcon({name: 'error'}),
    });
  }

  private getIcon({
    name,
    color = Toast.DEFAULT_ICON_COLOR,
    size = Toast.DEFAULT_ICON_SIZE,
  }: ToastIconConfig): Icon {
    const glyph = GlyphsMap[name]?.unicode?.[0];
    if (!name || !glyph) {
      throw new Error(`Invalid icon name: ${name}`);
    }

    return {
      glyph,
      fontName: 'iconfont',
      color,
      size,
    };
  }

  public showLoading(): void {
    try {
      NativeToast.makeToastActivity();
    } catch (error) {
      console.error('Failed to show loading toast:', error);
    }
  }

  public hideLoading(): void {
    try {
      NativeToast.hideToastActivity();
    } catch (error) {
      console.error('Failed to hide loading toast:', error);
    }
  }

  private show(options: CustomOptions): void {
    try {
      NativeToast.showCustomToast(options);
    } catch (error) {
      console.error('Failed to show toast:', error);
    }
  }
}

// 导出单例实例
const toast = Toast.getInstance();
export default toast;
